package ro.upt.dcda.web.admin;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.jms.StreamMessage;

import ro.upt.dcda.pricezone.common.JMSMediator;
import ro.upt.dcda.pricezone.common.ProductData;
import ro.upt.dcda.pricezone.common.Server;
import ro.upt.dcda.pricezone.s1.pojo.Admin;
import ro.upt.dcda.pricezone.s1.pojo.Product;
import ro.upt.dcda.pricezone.s1.requests.GetProductsRequest;

import com.opensymphony.xwork2.ActionContext;

public class AdminViewStoreServlet {

	private String id;
	private String server;
	private String name;
	private List<ProductData> products = new ArrayList<ProductData>();
	private List<String> allProducts = new ArrayList<String>();

	public List<ProductData> getProducts() {
		return products;
	}

	public void setProducts(List<ProductData> products) {
		this.products = products;
	}

	public String execute() throws Exception {
		System.out.println("Admin:Viewing store products.");
		Map<String, Object> session = ActionContext.getContext().getSession();
		Admin admin = (Admin) session.get("admin");
		String adminSid = (String) session.get("adminSid");
		if (admin == null || adminSid == null) {
			return "noAuth";
		}
		int storeId;
		try {
			storeId = Integer.valueOf(id);
		} catch (Exception ex) {
			ex.printStackTrace(System.out);
			return "def";
		}
		try {
			GetProductsRequest request = new GetProductsRequest();
			List<Product> allProductsData = request.work();
			for (Product temp : allProductsData) {
				allProducts.add(temp.getName());
			}
			Server s = JMSMediator.getMediator().getServerByName(this.server);
			StreamMessage msg = s.createStreamMessage();
			msg.writeString("prices");
			msg.writeInt(storeId);
			StreamMessage response = null;
			response = (StreamMessage) s.getResponseFor(msg, 30000);
			if (response == null) {
				return "def";
			}
			int nr = response.readInt();
			for (int i = 0; i < nr; i++) {
				ProductData data = new ProductData();
				int productID = response.readInt();
				for (Product temp : allProductsData) {
					if (temp.getId() == productID) {
						data.name = temp.getName();
						data.description = temp.getDescription();
						break;
					}
				}
				data.price = response.readString() + response.readString();
				products.add(data);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "def";
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getServer() {
		return server;
	}

	public void setServer(String server) {
		this.server = server;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getDefaultAllProducts() {
		return allProducts.size() > 0 ? allProducts.get(0) : "";
	}

	public List<String> getAllProducts() {
		return allProducts;
	}

	public void setAllProducts(List<String> allProd) {
		this.allProducts = allProd;
	}
}
